package kindergarden.at.google;

import java.sql.*;
import javax.swing.table.*;

/**
 * This class encapsulates a JDBC database connection and, given a SQL query
 * as a string, returns a ResultSetTableModel object suitable for display
 * in a JTable Swing component
 **/
public class DatabaseConnection
{
    static Connection connection;  // Holds the connection to the database

    public DatabaseConnection()throws ClassNotFoundException, SQLException
    {
        System.out.println("Setting up connection...");
//        String dbname = "jdbc:mysql://mmoo.no-ip.info:3306/ahuset";
//        String username = "PaRo";
//        String password = "patriklool";


//        String dbname = "jdbc:mysql://freesql.org:3306/databas";
//        String username = "datatek";
//        String password = "vinter2012";
        
         String dbname = "jdbc:mysql://db4free.net:3306/ahuset";
        String username = "datatek";
        String password = "vinter2012";

	// Now use that driver to connect to the database
	connection = DriverManager.getConnection(dbname, username, password);
    }


    /**
     * This method takes a SQL query, passes it to the database, obtains the
     * results as a ResultSet, and returns a ResultSetTableModel object that
     * holds the results in a form that the Swing JTable component can use.
     **/
    public MyTabelModel getResultSetTableModel(String query)throws SQLException
    {
	// If we've called close(), then we can't call this method
	if (connection == null)
	    throw new IllegalStateException("Connection already closed.");

	// Create a Statement object that will be used to excecute the query.
	// The arguments specify that the returned ResultSet will be 
	// scrollable, read-only, and insensitive to changes in the db.
	Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

	// Run the query, creating a ResultSet
	ResultSet r = statement.executeQuery(query);

	// Create and return a TableModel for the ResultSet
	return new MyTabelModel(r);
    }


    /** 
     * Call this method when done with the factory to close the DB connection 
     **/


    public void close()
    {
	try // Try to close the connection
        {
            connection.close();
        }
	catch (Exception e) {}      // Do nothing on error. At least we tried.
	connection = null; 
    }



    /** Automatically close the connection when we're garbage collected */
    @Override
    protected void finalize()
    {
        close();
    }
}
